
let db = require('../utils/DB');//数据库
let to = require('../utils/await-to-js');
let { SUCCESS, ERROR } = require('../utils/result');//结果
let { HOST } = require('../utils/CONSTANT');//常量模块

//底部八大板块
function homeModel() {
    return async (req, res) => {
        //1.获取板块数据
        let rst = await getHomeData();
        if (rst.length > 0) {
            //遍历数据源，取出重复的二级分类id数据
            let s = new Set();//保存不重复的second_id
            let arr = [];//保存返回给客户端的数据
            rst.forEach(item => {
                s.add(item.second_id);
            });
            let ps = [];//保存所有的promise
            //2.遍历set，根据second_id 来获取对应的商品数据
            [...s].forEach(id => {    //id 是遍历出来的二级id
                let obj = {};
                obj.thirdList = [];//二级分类下的所有的三级分类
                //遍历数据源，根据second_id,向对象中分拣数据
                rst.forEach(item => {
                    if (id == item.second_id) {
                        obj.second_id = item.second_id;//id
                        obj.image_url = item.image_url;//图片地址
                        obj.big_title = item.big_title;//大标题
                        obj.small_title = item.small_title;//小标题
                        obj.second_name = item.second_name;//二级分类名称  
                        obj.thirdList.push({
                            thired_id: item.thired_name,
                            thired_name: item.thired_name
                        });
                    }
                });
                arr.push(obj);//将板块数据添加到数组中
                //根据二级id获取4个对应的商品
                ps.push(getGoods(id));
            });

            //请求八个板块对应的商品数据
            let [err, data] = await to(Promise.all(ps));
            //遍历生成的数组，为每一个数组都添加goodsList属性
            arr.forEach((item, index) => {
                item.goodsList = data[index];
            });

            SUCCESS(res, arr);
        } else {
            ERROR(res, '板块数据获取失败', rst);
        }
    };
}


//获取八大板块数据
function getHomeData() {
    return db.query(`SELECT a.second_id,CONCAT(?,a.image_url) as image_url,a.big_title,a.small_title,b.second_name,c.thired_id,c.thired_name from home as a
    LEFT JOIN category_second as b ON a.second_id=b.second_id
    LEFT JOIN category_thired as c ON b.second_id=c.second_id`, [HOST]);
}

//根据二级分类id获取商品数据 (取四个数据)
function getGoods(id) {
    return db.query(`SELECT goods_id,goods_name,goods_manufacturer,CONCAT(?,image_url) as image_url FROM goods_list 
    WHERE second_id=?
    LIMIT 0,4`, [HOST, id]);
}


module.exports = homeModel;